package com.chuzhiyun.chengguoxy.feature.internship.clockin;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chuzhiyun.chengguoxy.R;
import com.chuzhiyun.chengguoxy.databinding.FragmentClockInStatisticsBinding;
import com.chuzhiyun.chengguoxy.feature.base.BaseFragment;
import com.chuzhiyun.chengguoxy.feature.bean.AttendanceBean;
import com.chuzhiyun.chengguoxy.feature.bean.ProjectListBean;
import com.chuzhiyun.chengguoxy.feature.bean.PunchDayBean;
import com.chuzhiyun.chengguoxy.feature.internship.clockin.Canendar.TicketPainter;
import com.chuzhiyun.chengguoxy.network.NetApi;
import com.chuzhiyun.chengguoxy.network.NetService;
import com.chuzhiyun.chengguoxy.network.StringNetCallback;
import com.chuzhiyun.chengguoxy.utlis.CustomClickListener;
import com.chuzhiyun.chengguoxy.utlis.StringUtils;
import com.chuzhiyun.chengguoxy.utlis.TimeUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.necer.calendar.BaseCalendar;
import com.necer.enumeration.CalendarState;
import com.necer.enumeration.DateChangeBehavior;
import com.necer.listener.OnCalendarChangedListener;
import com.necer.listener.OnCalendarStateChangedListener;

import org.jetbrains.annotations.NotNull;
import org.joda.time.LocalDate;

import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class ClockInStatisticsFragment extends BaseFragment<FragmentClockInStatisticsBinding> {

    private String chooseDateStr;
    private ImageView animationImg;
    private ClockInStatisticsFragment.MyAdapter myAdapter;
    private List<PunchDayBean> dataSource = new ArrayList<PunchDayBean>();
    private List<AttendanceBean> attendanceList = new ArrayList<AttendanceBean>();
    private String dateMin;
    private String dateMax;


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void initView(View view) {
        binding.navView.ivBack.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                requireActivity().finish();
            }
        });
        binding.navView.tvTitle.setText("统计");
        binding.calendarLeft.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                binding.calendarView.toLastPager();
            }
        });
        binding.calendarRight.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                binding.calendarView.toNextPager();
            }
        });

        binding.calendarView.setOnCalendarStateChangedListener(new OnCalendarStateChangedListener() {
            @Override
            public void onCalendarStateChange(CalendarState calendarState) {
                if (calendarState.getValue()==100)
                {
                    animationImg.setImageResource(R.mipmap.arrow_down_data);
                }
                else
                {
                    animationImg.setImageResource(R.mipmap.arrow_up_data);
                }
            }
        });

        binding.calendarView.setOnCalendarChangedListener(new OnCalendarChangedListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @SuppressLint("SetTextI18n")
            @Override
            public void onCalendarChange(BaseCalendar baseCalendar, int year, int month, LocalDate localDate, DateChangeBehavior dateChangeBehavior) {
                binding.tvTitleYear.setText(year + "年" + month + "月");
                binding.monthTopText.setText(month+"月出勤统计");
                chooseDateStr = localDate.toString();
                getPunchFixList(chooseDateStr);

                String newTimeStr = localDate.toString();
                System.out.println(newTimeStr);
                String startTime0 = newTimeStr.substring(0,8);
                System.out.println(startTime0);
                dateMin = startTime0+"01";
                int endDays = getDaysByYearMonth(year,month);
                dateMax = startTime0+endDays+"";

                getAttends();
            }
        });

        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
        myAdapter = new MyAdapter(R.layout.item_statistical, dataSource);
        binding.recyclerView.setAdapter(myAdapter);
        setHeader(binding.recyclerView);
    }

    /**
     * 根据 年、月 获取对应的月份 的 天数
     */
    private int getDaysByYearMonth(int year, int month) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        return a.get(Calendar.DATE);
    }

    private void getAttends(){
        String url = NetApi.getAttendanceList();
        HashMap<String,String>param = new HashMap<>();
        param.put("start",dateMin);
        param.put("end",dateMax);
        param.put("project","1");

        attendanceList.clear();

        NetService.getInstance().getParam(url, param, new StringNetCallback() {
            @Override
            public void onSuccess(String response, int statusCode) throws Exception {
                System.out.println(response);
                if (statusCode==200){
                    Gson gson = new Gson();
                    attendanceList = gson.fromJson(response, new TypeToken<List<AttendanceBean>>() {
                    }.getType());
                    System.out.println(attendanceList);
                    calendarColor();
                }
            }

            @Override
            public void onError(String error) {
                System.out.println(error);
            }
        });
    }

    /*设置日历的标记颜色*/
    private void calendarColor()
    {
        Map<LocalDate, String> priceMap = new HashMap<>();
        TicketPainter ticketPainter = new TicketPainter(getContext(), binding.calendarView);
        for (int i=0;i<attendanceList.size();i++)
        {
            AttendanceBean beans = attendanceList.get(i);
            priceMap.put(new LocalDate(beans.getDate()), beans.getAttendance());
            ticketPainter.setPriceMap(priceMap);
        }
        binding.calendarView.setCalendarPainter(ticketPainter);
    }

    @Override
    public void onResume() {
        super.onResume();
        chooseDateStr = TimeUtils.getCurrentTime();
        getPunchFixList(chooseDateStr);
    }

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {

    }

    private void getPunchFixList(String date){
        String url = NetApi.getPunchList();
        HashMap<String, String> param = new HashMap<>();
        param.put("date",date);
        NetService.getInstance().getParam(url, param, new StringNetCallback() {
            @SuppressWarnings("deprecation")
            @Override
            public void onSuccess(String response, int statusCode) throws Exception {
                System.out.println(response);
                if (statusCode==200){
                    dataSource.clear();
                    Gson gson = new Gson();
                    dataSource = gson.fromJson(response, new TypeToken<List<PunchDayBean>>() {
                    }.getType());
                    myAdapter.setNewData(dataSource);
                    myAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(String error) {
                System.out.println(error);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @SuppressLint("DefaultLocale")
    private void setHeader(RecyclerView view) {
        View header = LayoutInflater.from(getActivity()).inflate(R.layout.statistical_header, view, false);
        animationImg = header.findViewById(R.id.animation_Img);
        TextView supplementText = header.findViewById(R.id.supplement_Text);
        supplementText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                Intent intent = new Intent();
                intent.setClass(getContext(),RetroactiveActivity.class);
                intent.putExtra("date",chooseDateStr);
                startActivity(intent);
            }
        });
        myAdapter.setHeaderView(header);
    }

    public static class MyAdapter extends BaseQuickAdapter<PunchDayBean, BaseViewHolder> {

        public MyAdapter(int layoutResId, List<PunchDayBean> data) {
            super(layoutResId, data);
        }

        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        protected void convert(@NotNull BaseViewHolder helper, PunchDayBean item) {
            String strs = item.getDate();
            String newStr = strs.substring(11,16);
            helper.setText(R.id.leaveIntervalLabel, "打卡："+newStr);
            helper.setText(R.id.address_Text, "打卡地点:"+item.getStreet());
            if (item.getMood().equals("good")){
                helper.setText(R.id.message_Text, "打卡心情:心情愉悦");
            }
            if (item.getMood().equals("moderate")){
                helper.setText(R.id.message_Text, "打卡心情:心情还行");
            }
            if (item.getMood().equals("bad")){
                helper.setText(R.id.message_Text, "打卡心情:心情不爽");
            }
            if (StringUtils.isEmpty(item.getPicture()))
            {
                //图片不存在
                helper.setGone(R.id.showImg_Text,true);
            }
            else
            {
                //图片存在
                helper.setVisible(R.id.showImg_Text,true);
            }
        }
    }

}